package com.hncgy.xzf.jdapi.controller.product;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hncgy.xzf.jdapi.domain.product.po.Categories;
import com.hncgy.xzf.jdapi.mapper.product.CategoriesMapper;
import com.hncgy.xzf.jdapi.tool.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 商品分类表 前端控制器
 * </p>
 *
 * @author 不会代码的蜡笔
 * @since 2025-10-31
 */
@RestController
@RequestMapping("/product/categories")
public class CategoriesController {

    @Autowired
    private CategoriesMapper categoriesMapper;

    //查询商品分类
    @GetMapping("/list")
    public Result<List<Categories>> list(Categories categories) {
        try {
            QueryWrapper<Categories> categoriesQueryWrapper = new QueryWrapper<>();
            categoriesQueryWrapper.lambda()
                    .like(StringUtils.hasText(categories.getCategoryName()), Categories::getCategoryName, categories.getCategoryName());
            List<Categories> data = categoriesMapper.selectList(categoriesQueryWrapper);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    //新增商品分类
    @PostMapping("/create")
    public Result<Boolean> create(@RequestBody Categories categories) {
        try {
            int result = categoriesMapper.insert(categories);
            if (result > 0) {
                return Result.success(true);
            } else {
                return Result.error("新增失败");
            }
        } catch (Exception e) {
            return Result.error("新增失败: " + e.getMessage());
        }
    }

    //修改商品分类
    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody Categories categories) {
        try {
            int result = categoriesMapper.updateById(categories);
            if (result > 0) {
                return Result.success(true);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    //删除商品分类
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Integer id) {
        try {
            int result = categoriesMapper.deleteById(id);
            if (result > 0) {
                return Result.success(true);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败: " + e.getMessage());
        }
    }

}
